#!/usr/bin/env python3

import base64
import hashlib
import hmac
import http.client
import json
import sys
import time
import urllib.parse

import cred

# Product
# ENDPOINT = 'api.international.coinbase.com'

# Sandbox
ENDPOINT = 'api-n5e1.coinbase.com'


def rest_api(url_path, method='GET', **body_params):
    ts_sec = str(int(time.time()))
    url = f'https://{ENDPOINT}{url_path}'
    body = json.dumps(body_params)
    message = ts_sec + method + urllib.parse.urlparse(url).path + str(body)
    signature = hmac.new(cred.SECRET, message.encode('utf-8'),
                         digestmod=hashlib.sha256).digest()
    signature_b64 = base64.b64encode(signature).decode()

    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'CB-ACCESS-TIMESTAMP': ts_sec,
        'CB-ACCESS-SIGN': signature_b64,
        'CB-ACCESS-PASSPHRASE': cred.PASSPHRASE,
        'CB-ACCESS-KEY': cred.ACCESS_KEY
    }

    conn = http.client.HTTPSConnection(ENDPOINT)
    request = dict(
        method=method,
        url=url_path,
        body=body,
        headers=headers
    )
    print(f'>>> {json.dumps(request, indent=2)}')
    conn.request(method, url_path, body, headers)
    response = json.loads(conn.getresponse().read().decode())
    print(f'<<< {json.dumps(response, indent=2)}')
    return response


def test():
    print(f'SECRET={cred.SECRET.decode()}')
    portfolio_id = rest_api('/api/v1/portfolios')[0]['portfolio_id']
    rest_api('/api/v1/assets')
    rest_api('/api/v1/instruments')
    rest_api(f'/api/v1/portfolios/{portfolio_id}/detail')
    # rest_api('/api/v1/orders', 'POST',
    #          client_order_id=str(int(time.time())),
    #          side='BUY',
    #          size=1,
    #          tif='GTC',
    #          instrument='BTC-USDC',
    #          type='LIMIT',
    #          price=52303,
    #          portfolio=portfolio_id,
    #          post_only=True)
    # orders = rest_api(f'/api/v1/orders?portfolio={portfolio_id}')['results']
    # for order in orders:
    #     rest_api(
    #         f'/api/v1/orders/{order["client_order_id"]}?portfolio={portfolio_id}', 'DELETE')
    # rest_api(f'/api/v1/orders?portfolio={portfolio_id}')
    # rest_api(f'/api/v1/portfolios/{portfolio_id}/detail')
    return 0


if __name__ == '__main__':
    sys.exit(test())
